package com.hzlh.core.utils;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import org.apache.log4j.Logger;

/**
 * 文件工具
 * 
 * @since
 */

public class FileUtils extends org.apache.commons.io.FileUtils {
	private static final Logger logger = Logger.getLogger(FileUtils.class);

	/**
	 * 将内容写入文件，如果文件不存在，则创建一个新文件
	 * 
	 * @param targetPath
	 *            写入的文件物理路径
	 * @param fileContent
	 *            写入的文件内容
	 */
	public static void writeFile(String targetPath, String fileContent,String webencoding) {
		File file = new File(targetPath);
		PrintWriter out = null;
		try {
			if (!file.exists()) {
				File parent = file.getParentFile();
				if (parent.exists() || parent.mkdirs()) {
					file.createNewFile();
				}
			}
			out = new PrintWriter(file, webencoding);
			out.print(fileContent);
		} catch (IOException e) {
			logger.error(e);
			throw new IllegalStateException(e);
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	/**
	 * 
	 * @param targetPath
	 * @return 文件内容
	 */
	public static String readFile(String targetPath) {
		StringBuffer sb = new StringBuffer();
		File file = new File(targetPath);
		FileReader read = null;
		BufferedReader in = null;
		try {
			read = new FileReader(file);
			in = new BufferedReader(read);
			String s = null;
			while ((s = in.readLine()) != null) {
				sb.append(s);
				sb.append("\n");
			}
		} catch (IOException e) {
			logger.error(e);
			throw new IllegalStateException(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e2) {
					logger.error(e2);
				}
			}
		}
		return sb.toString();
	}

	/**
	 * 删除文件
	 * 
	 * @param f
	 */
	public static boolean deleteFile(File f) {

		if (f.isFile()) {
			f.delete();
		}
		return true;
	}

	/**
	 * 删除文件
	 * <p>
	 * 
	 * @param filePath
	 * @return
	 */
	public static boolean deleteFile(String filePath) {
		return deleteFile(new File(filePath));
	}

	/**
	 * 删除文件夹
	 * 
	 * @param f
	 */
	public static boolean deleteDir(File f) {
		if (f.isDirectory()) {
			File[] files = f.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					deleteDir(files[i]);
				}
			}
		}
		f.delete();
		return true;
	}

	/**
	 * 删除文件夹
	 * <p>
	 * 
	 * @param dir
	 * @return
	 */
	public static boolean deleteDir(String dir) {
		return deleteDir(new File(dir));
	}

	// /**
	// * 得到指定文件夹下，指定文件夹名前缀的所有文件夹,除了excludeDir
	// *
	// * @param dir
	// * @param namePrefix
	// * @param excludeDir
	// * @return
	// */
	// public static List getDirByNameprefix(File dir, String namePrefix,
	// String excludeDir) {
	// List dirList = new ArrayList();
	// if (dir.isDirectory()) {
	// File[] files = dir.listFiles();
	// for (int i = 0; i < files.length; i++) {
	// if (!files[i].isDirectory()
	// || files[i].getName().equals(excludeDir))
	// continue;
	// if (files[i].getName().startsWith(namePrefix))
	// dirList.add(files[i]);
	// }
	// }
	// return dirList;
	// }
	//
	/**
	 * 文件重命名
	 * 
	 * @param oldFile
	 * @param newFileName
	 * @return
	 */
	public static boolean renameFile(File oldFile, String newFileName) {
		if (oldFile.isFile()) {
			oldFile.renameTo(new File(oldFile.getAbsolutePath().substring(0,
					oldFile.getAbsolutePath().lastIndexOf(File.separator) + 1)
					+ newFileName));
		}
		return true;
	}

	/**
	 * 
	 * <p>
	 * 
	 * @param oldFile
	 * @param newFileName
	 * @return
	 */
	public static boolean renameFile(String oldFile, String newFileName) {
		return renameFile(new File(oldFile), newFileName);
	}

	//
	// /**
	// * 文件夹重命名
	// *
	// * @param oldDir
	// * @param newDirName
	// * @return
	// */
	// public static boolean renameDir(File oldDir, String newDirName) {
	// if (oldDir.isDirectory()) {
	// oldDir.renameTo(new File(oldDir.getAbsolutePath().substring(0,
	// oldDir.getAbsolutePath().lastIndexOf(File.separator) + 1)
	// + newDirName));
	// }
	// return true;
	// }
	//
	/**
	 * 将源文件复制一份到目标文件
	 * 
	 * @param srcFile
	 *            源文件全路径
	 * @param targetFile
	 *            目标文件全路径
	 */
	public static void copyFile(String srcFile, String targetFile) {
		targetFile = targetFile.replace("/", File.separator);
		String targetDir = targetFile.substring(0, targetFile.lastIndexOf(File.separator)); // 提取文件路径
		File f = new File(targetDir); // 建立文件目录路
		if (!f.exists()) {
			f.mkdirs();
		}

		BufferedInputStream inputStream = null;
		BufferedOutputStream outputStream = null;

		try {
			inputStream = new BufferedInputStream(new FileInputStream(srcFile));
			outputStream = new BufferedOutputStream(new FileOutputStream(targetFile));
			int c;
			while ((c = inputStream.read()) != -1) { // 复制
				outputStream.write(c);
			}
		} catch (IOException e) {
			logger.error(e);
			throw new IllegalStateException(e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					logger.error(e);
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					logger.error(e);
				}
			}
		}
	}
	
	/**
	 * 
	 * <p>
	 * 
	 * @param outImagePath
	 */
	public static void mkdirs(String outFilePath) {		
		File file = new File(outFilePath);
		File dir = file.getParentFile();
		if (!dir.exists()) {
			dir.mkdirs();
		}
	}
	
	/**
	 * 文件名加后缀
	 * <p>
	 * 
	 * @param fileName
	 * @param suffix
	 * @return
	 */
	public static String fileNameAddSuffix(String fileName, String suffix) {	
		int p = fileName.lastIndexOf(".");
		String fileName1 = fileName.substring(0, p);
		String extName = fileName.substring(p);
		return fileName1 + suffix + extName;
	}
}
